package at.ac.tuwien.swa.sparrow.peer.component

import ac.at.tuwien.infosys.swa.audio.Fingerprint
import at.ac.tuwien.swa.sparrow.common.TrackInfo
import com.typesafe.scalalogging.log4j.Logging
import javax.inject.Inject
import org.jaudiotagger.audio.AudioFileIO
import org.jaudiotagger.tag.FieldKey._
import org.springframework.stereotype.Component
import scala.reflect.io.{Path, File, Directory}

@Component
class IndexingWorker @Inject()(database: MusicLibrary, fun: AudioFingerprintFunction) extends Logging {

	val supportedTypes = {"mp3"}

	java.util.logging.LogManager.getLogManager.readConfiguration(
		new java.io.ByteArrayInputStream("org.jaudiotagger.level = WARNING".getBytes))

	def scan(dir: String) {
		scan(Path(dir).toDirectory)
	}

	def scan(dir: Directory) {
		logger.info(s"Scanning directory ${dir.toAbsolute}")
		dir.deepFiles filter (_ hasExtension supportedTypes) foreach index
	}

	def index(f: File) {
		val fingerprint = fun(f)
		database += (fingerprint -> readName(f, fingerprint))
	}

	def readTag(f: File) = (AudioFileIO read f.jfile).getTag

	def readName(f: File, fingerprint: Fingerprint) = {
		logger.debug(s"Extracting tag information from ${f.toAbsolute.path}")
		val tag = readTag(f)
		val artist = if (tag hasField ALBUM_ARTIST.name()) tag getFirst ALBUM_ARTIST else tag getFirst ARTIST
		new TrackInfo(fingerprint, tag getFirst TITLE, artist, tag getFirst ALBUM)
	}
}
